package cn.jiahua.test14;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Test1 {

    public static void main(String[] args) {
        MyCacheLock myCache=new MyCacheLock();
        for (int i=0;i<10;i++){
            new Thread(()->{
                myCache.put(Thread.currentThread().getName(),"a");
            }).start();

            new Thread(()->{
                myCache.get(Thread.currentThread().getName());
            }).start();
        }
    }
}
/*
        * 存数据到map里面
        * 从map中取数据
        */
class MyCacheLock{
    private volatile Map<String,Object> map=new ConcurrentHashMap<>();
    //    Lock lock =new ReentrantLock();
    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    public void put(String key ,Object object){
        Lock writeLock=  readWriteLock.writeLock();
        try{
            writeLock.lock();
            System.out.println(Thread.currentThread().getName()+"写入数据："+key);
            map.put(key,object);

            System.out.println(Thread.currentThread().getName()+"写入数据ok");
        }catch (Exception e){

        }finally {
            writeLock.unlock();
        }

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


    public void get(String key){
        Lock readLockLock=  readWriteLock.readLock();
        try{
            //读读不存在互斥
            readLockLock.lock();
            System.out.println(Thread.currentThread().getName()+"读取数据："+key);
            Object o =map.get(key);
            TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName()+"读取数据ok");
        }catch (Exception e){

        }finally {
           readLockLock.unlock();
        }
    }


}


